package day1.Exer527;

import day1.Exer.DBUtil;

import java.sql.*;
import java.util.Scanner;

/**
 *  insert操作支持返回主键
 */
public class Exer2 {
    public static void main(String[] args) {
        Scanner in=new Scanner(System.in);
        System.out.println("请输入要插入的姓名");
        String name=in.next();
        System.out.println("请输入班级编号");
        int gradeid=in.nextInt();
        System.out.println("对应主键的值为"+getPrimarykey(name,gradeid));
        }



    public static int getPrimarykey(String name,int gradeid){
        Connection con=null;
        String pkname=null;
        int pkvalue=0;
        try {
            String sql1="insert into s_student(`sname`,`gradeid`) values (?,?)";
            con= DBUtil.getConnection();
            DatabaseMetaData metaData = con.getMetaData();
            ResultSet rs3=metaData.getPrimaryKeys("exer",null,"s_student");
            while(rs3.next()){
                //获得主键列的列名
                pkname=rs3.getString("COLUMN_NAME");
            }
            PreparedStatement pst1=con.prepareStatement(sql1);
            pst1.setString(1,name);
            pst1.setInt(2,gradeid);
            int rs=pst1.executeUpdate();
            String sql2="Select "+pkname+" from s_student where sname='"+name+"'";
            PreparedStatement pst2=con.prepareStatement(sql2);
            ResultSet rs2=pst2.executeQuery();
            while(rs2.next()){
                pkvalue=rs2.getInt(pkname);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return pkvalue;
    }
}
